package com.cy.aircompressor.utils;

import android.app.AppOpsManager;
import android.app.usage.NetworkStats;
import android.app.usage.NetworkStatsManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.os.Build;
import android.os.RemoteException;
import android.provider.Settings;

import com.drug.lib.util.DLog;

import static android.content.Context.NETWORK_STATS_SERVICE;

public class UsageUtil {


    public static boolean hasPermissionToReadNetworkStats(Context context) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        }
        final AppOpsManager appOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
        int mode = appOps.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS,
                android.os.Process.myUid(), context.getPackageName());
        if (mode == AppOpsManager.MODE_ALLOWED) {
            return true;
        }

        requestReadNetworkStats(context);
        return false;
    }

    // 打开“有权查看使用情况的应用”页面
    private static void requestReadNetworkStats(Context context) {
        Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
        context.startActivity(intent);
    }

    //应用包名查uid
    public static int getUidByPackageName(Context context, String packageName) {
        int uid = -1;
        PackageManager packageManager = context.getPackageManager();
        try {
            PackageInfo packageInfo = packageManager.getPackageInfo(packageName, PackageManager.GET_META_DATA);

            uid = packageInfo.applicationInfo.uid;
            DLog.d(packageInfo.packageName + " uid:" + uid);


        } catch (PackageManager.NameNotFoundException e) {
        }

        return uid;
    }

    /**
     * 获取uid （单个）应用流量
     *
     * @param context   上下文
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param uid       应用uid
     */
    public static Usage getUsageBytesByUid(Context context, long startTime, long endTime, int uid) {
        Usage usage = new Usage();
        usage.totalRxBytes = 0;
        usage.totalTxBytes = 0;
        usage.mobleRxBytes = 0;
        usage.mobleTxBytes = 0;
        usage.wifiTxBytes = 0;
        usage.wifiTxBytes = 0;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            NetworkStatsManager nsm = (NetworkStatsManager) context.getSystemService(NETWORK_STATS_SERVICE);
            assert nsm != null;
            NetworkStats wifi = nsm.queryDetailsForUid(ConnectivityManager.TYPE_WIFI, null, startTime, endTime, uid);
            NetworkStats moble = nsm.queryDetailsForUid(ConnectivityManager.TYPE_MOBILE, null, startTime, endTime, uid);
            do {
                NetworkStats.Bucket bucket = new NetworkStats.Bucket();
                wifi.getNextBucket(bucket);
                usage.wifiRxBytes += bucket.getRxBytes();
                usage.wifiTxBytes += bucket.getTxBytes();
            } while (wifi.hasNextBucket());
            do {
                NetworkStats.Bucket bucket = new NetworkStats.Bucket();
                moble.getNextBucket(bucket);
                usage.mobleRxBytes += bucket.getRxBytes();
                usage.mobleTxBytes += bucket.getTxBytes();
            } while (moble.hasNextBucket());
            usage.wifiTotalData = usage.wifiRxBytes + usage.wifiTxBytes;
            usage.mobleTotalData = usage.mobleRxBytes + usage.mobleTxBytes;
        }
        return usage;
    }


    /**
     * 获取单个应用流量
     *
     * @param context   上下文
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param uid       统计应用uid
     */
    public static Usage getApplicationQuerySummary(Context context, long startTime, long endTime, int uid) {
        Usage usage = new Usage();
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            NetworkStatsManager nsm = (NetworkStatsManager) context.getSystemService(NETWORK_STATS_SERVICE);
            assert nsm != null;
            try {
                NetworkStats wifi = nsm.querySummary(ConnectivityManager.TYPE_WIFI, null, startTime, endTime);
                NetworkStats mobile = nsm.querySummary(ConnectivityManager.TYPE_MOBILE, null, startTime, endTime);
                do {
                    NetworkStats.Bucket bucket = new NetworkStats.Bucket();
                    wifi.getNextBucket(bucket);
                    if (bucket.getUid() == uid) {
                        usage.wifiRxBytes += bucket.getRxBytes();
                        usage.wifiTxBytes += bucket.getTxBytes();
                    }
                } while (wifi.hasNextBucket());

                do {
                    NetworkStats.Bucket bucket = new NetworkStats.Bucket();
                    mobile.getNextBucket(bucket);
                    if (bucket.getUid() == uid) {
                        usage.mobleRxBytes += bucket.getRxBytes();
                        usage.mobleTxBytes += bucket.getTxBytes();
                    }
                } while (mobile.hasNextBucket());
                usage.wifiTotalData = usage.wifiRxBytes + usage.wifiTxBytes;
                usage.mobleTotalData = usage.mobleRxBytes + usage.mobleTxBytes;
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        return usage;
    }

    /**
     * 获取单个应用流量
     *
     * @param context
     * @param startTime
     * @param endTime
     * @param uid
     */
    public static Usage getApplicationQueryDetails(Context context, long startTime, long endTime, int uid) {
        Usage usage = new Usage();
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            NetworkStatsManager nsm = (NetworkStatsManager) context.getSystemService(NETWORK_STATS_SERVICE);
            assert nsm != null;
            try {
                NetworkStats wifi = nsm.queryDetails(ConnectivityManager.TYPE_WIFI, null, startTime, endTime);
                NetworkStats mobile = nsm.queryDetails(ConnectivityManager.TYPE_MOBILE, null, startTime, endTime);
                do {
                    NetworkStats.Bucket bucket = new NetworkStats.Bucket();
                    wifi.getNextBucket(bucket);
                    if (bucket.getUid() == uid) {
                        usage.wifiRxBytes += bucket.getRxBytes();
                        usage.wifiTxBytes += bucket.getTxBytes();
                    }
                } while (wifi.hasNextBucket());
                do {
                    NetworkStats.Bucket bucket = new NetworkStats.Bucket();
                    mobile.getNextBucket(bucket);
                    if (bucket.getUid() == uid) {
                        usage.mobleRxBytes += bucket.getRxBytes();
                        usage.mobleTxBytes += bucket.getTxBytes();
                    }
                } while (mobile.hasNextBucket());
                usage.wifiTotalData = usage.wifiRxBytes + usage.wifiTxBytes;
                usage.mobleTotalData = usage.mobleRxBytes + usage.mobleTxBytes;
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        return usage;
    }


}
